from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from hashlib import sha256
import time
import hmac
import base64
import requests
import json
import urllib


def logins(request):
    return render(request, 'dd_login_auth/login.html')

def transfer(request):
    sns_code = request.GET.get('code')
    sns_state = request.GET.get('state')
    sns_appsecret = 'appsecret' # 钉钉扫码登录的appSecret
    t = time.time()
    timestamp = str((int(round(t * 1000))))
    signature = base64.b64encode(hmac.new(sns_appsecret.encode('utf-8'), timestamp.encode('utf-8'), digestmod=sha256).digest())
    payload = {'tmp_auth_code': sns_code}
    headers = {'Content-Type': 'application/json'}
    r = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature=' + urllib.parse.quote(signature.decode("utf-8")) + "&timestamp=" + timestamp + "&accessKey=appid", data=json.dumps(payload), headers=headers) # accessKey为钉钉扫码登录的appId
    try:
        if json.loads(r.text)['user_info']['nick'] == '王磊':
            # redirect_to = request.GET.get('next', '/dd/dd_index')
            # return HttpResponseRedirect(redirect_to)
            return HttpResponse(r.text)
    except:
        return HttpResponse('登录失败')

def index(request):
    return HttpResponse('欢迎来到钉钉扫码后的首页')